<template>
  <div class="page-wrapper">
    <!-- 步骤条区域 -->
    <div class="step-container">
      <el-steps
        style="width: 100%"
        align-center
        :active="activeStep"
        finish-status="success"
        @step-click="handleStepClick"
      >
        <el-step title="申请入住" status="success" />
        <el-step title="入住评估" status="success" />
        <el-step title="入住审批" status="success" />
        <el-step title="入住配置" status="success" />
        <el-step title="签约办理" status="success" />
      </el-steps>
    </div>

    <!-- 数据详情区域 -->
    <div class="detail-container">
      <!-- 1. 基础信息卡片 -->
      <el-card class="detail-card" shadow="hover" border>
        <template #header>
          <div class="card-header">
            <i class="el-icon-info-circle card-icon"></i>
            <span class="card-title">基础信息</span>
          </div>
        </template>
        <div class="card-content">
          <div class="info-list">
            <div class="info-item">
              <label class="info-label">入住编号</label>
              <span class="info-value">{{ ruzhuData.checkInNo || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">老人姓名</label>
              <span class="info-value">{{ ruzhuData.elderlyName || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">身份证号</label>
              <span class="info-value">{{ ruzhuData.elderlyIdCard || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">护理等级</label>
              <span class="info-value">
                {{ ruzhuData.nursingLevelName || "-" }}
                <span v-if="ruzhuData.nursingLevelFee" class="text-primary">
                  (¥{{ ruzhuData.nursingLevelFee }})
                </span>
              </span>
            </div>
            <div class="info-item">
              <label class="info-label">床位编号</label>
              <span class="info-value">{{ ruzhuData.bedNo || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">办理人</label>
              <span class="info-value">{{ ruzhuData.creatorNickName || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">办理时间</label>
              <span class="info-value">{{ formatDate(ruzhuData.createTime) || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">入住周期</label>
              <span class="info-value">
                {{ formatDate(ruzhuData.checkInStartTime) || "-" }} -
                {{ formatDate(ruzhuData.checkInEndTime) || "-" }}
              </span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 2. 费用信息卡片 -->
      <el-card class="detail-card" shadow="hover" border>
        <template #header>
          <div class="card-header">
            <i class="el-icon-money card-icon"></i>
            <span class="card-title">费用信息</span>
          </div>
        </template>
        <div class="card-content">
          <div class="info-list">
            <div class="info-item">
              <label class="info-label">费用周期</label>
              <span class="info-value">
                {{ formatDate(ruzhuData.feeStartDate) || "-" }} -
                {{ formatDate(ruzhuData.feeEndDate) || "-" }}
              </span>
            </div>
            <div class="info-item">
              <label class="info-label">押金</label>
              <span class="info-value text-primary">¥{{ ruzhuData.deposit || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">护理费用</label>
              <span class="info-value text-primary">¥{{ ruzhuData.nursingFee || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">床位费用</label>
              <span class="info-value text-primary">¥{{ ruzhuData.bedFee || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">其他费用</label>
              <span class="info-value text-primary">¥{{ ruzhuData.otherFee || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">医保支付</label>
              <span class="info-value text-success">¥{{ ruzhuData.medicalInsurancePayment || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">政府补贴</label>
              <span class="info-value text-success">¥{{ ruzhuData.governmentSubsidy || 0 }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">费用合计</label>
              <span class="info-value text-danger font-bold">¥{{ calculateTotalFee() }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 3. 评估信息卡片 -->
      <el-card class="detail-card" shadow="hover" border>
        <template #header>
          <div class="card-header">
            <i class="el-icon-stethoscope card-icon"></i>
            <span class="card-title">入住评估</span>
          </div>
        </template>
        <div class="card-content">
          <div class="assessment-wrap">
            <!-- 健康评估 -->
            <div class="assessment-item">
              <h4 class="assessment-title">健康评估</h4>
              <div class="info-list">
                <div class="info-item">
                  <label class="info-label">评估时间</label>
                  <span class="info-value">{{ formatDate(ruzhuData.haCreateTime) || "-" }}</span>
                </div>
                <div class="info-item">
                  <label class="info-label">疾病诊断</label>
                  <span class="info-value">{{ getDiseaseDiagnosis() || "-" }}</span>
                </div>
                <div class="info-item">
                  <label class="info-label">自理能力</label>
                  <span class="info-value">{{ getSelfCareAbilityText() || "-" }}</span>
                </div>
                <div class="info-item">
                  <label class="info-label">用药情况</label>
                  <span class="info-value">{{ getMedicationText() }}</span>
                </div>
              </div>
            </div>

            <!-- 能力评估 -->
            <div class="assessment-item">
              <h4 class="assessment-title">能力评估</h4>
              <div class="info-list">
                <div class="info-item">
                  <label class="info-label">自理能力得分</label>
                  <span class="info-value">{{ ruzhuData.selfCareScore || 0 }} 分</span>
                </div>
                <div class="info-item">
                  <label class="info-label">精神状态得分</label>
                  <span class="info-value">{{ ruzhuData.mentalStatusScore || 0 }} 分</span>
                </div>
                <div class="info-item">
                  <label class="info-label">综合得分</label>
                  <span class="info-value">{{ ruzhuData.estimatedTotalScore || 0 }} 分</span>
                </div>
                <div class="info-item">
                  <label class="info-label">能力等级</label>
                  <span class="info-value">{{ ruzhuData.finalAbilityLevel || "-" }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 4. 合同信息卡片 -->
      <el-card class="detail-card" shadow="hover" border>
        <template #header>
          <div class="card-header">
            <i class="el-icon-file-contract card-icon"></i>
            <span class="card-title">合同信息</span>
          </div>
        </template>
        <div class="card-content">
          <div class="info-list">
            <div class="info-item">
              <label class="info-label">合同名称</label>
              <span class="info-value">{{ ruzhuData.contractName || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">合同编号</label>
              <span class="info-value">{{ ruzhuData.contractNo || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">合同状态</label>
              <span class="info-value">
                <el-tag :type="getContractTagType()">{{ ruzhuData.contractStatus || "-" }}</el-tag>
              </span>
            </div>
            <div class="info-item">
              <label class="info-label">签约时间</label>
              <span class="info-value">{{ formatDate(ruzhuData.signTime) || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">合同周期</label>
              <span class="info-value">
                {{ formatDate(ruzhuData.contractStartDate) || "-" }} -
                {{ formatDate(ruzhuData.contractEndDate) || "-" }}
              </span>
            </div>
            <div class="info-item">
              <label class="info-label">丙方联系人</label>
              <span class="info-value">{{ ruzhuData.partyCName || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">联系电话</label>
              <span class="info-value">{{ ruzhuData.partyCPhone || "-" }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">合同文件</label>
              <span class="info-value">
                <el-link
                  v-if="ruzhuData.contractFile"
                  :href="ruzhuData.contractFile"
                  target="_blank"
                  type="primary"
                >
                  查看合同 <i class="el-icon-arrow-right el-icon--small"></i>
                </el-link>
                <span v-else>-</span>
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// 关键修复：正确引入并获取路由实例
import { useRoute } from "vue-router";
import { getRuzhuDto } from "@/api/rutui/ruzhu";
import { ElMessage, ElTag, ElLink } from "element-plus";

// 关键修复：通过 useRoute() 获取路由实例并赋值给变量
const route = useRoute();
// 初始化数据为对象，避免undefined
const ruzhuData = ref({});
const activeStep = ref(5);

onMounted(() => {
  // 现在可以正常使用 route 变量获取查询参数
  const id = route.query.id;
  console.log("当前路由中的id：", id); 
  if (!id) {
    ElMessage.error("未获取到入住记录ID，无法加载详情");
    return;
  }

  // 加载数据
  getRuzhuDto(id)
    .then((response) => {
      ruzhuData.value = response.data || {};
    })
    .catch((error) => {
      ElMessage.error("加载入住详情失败，请稍后重试");
      console.error("详情加载错误：", error);
      ruzhuData.value = {}; // 确保始终是对象
    });
});

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr || typeof dateStr !== "string") return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return "";
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
};

// 处理疾病诊断
const getDiseaseDiagnosis = () => {
  try {
    const diagnosis = JSON.parse(ruzhuData.value.diseaseDiagnosis || "{}");
    return Array.isArray(diagnosis.selected) && diagnosis.selected.length
      ? diagnosis.selected.join("、")
      : "";
  } catch (e) {
    console.error("疾病诊断解析失败:", e);
    return "";
  }
};

// 处理自理能力
const getSelfCareAbilityText = () => {
  try {
    const selfCare = JSON.parse(ruzhuData.value.haSelfCareAbility || "{}");
    return selfCare.result || "";
  } catch (e) {
    console.error("自理能力解析失败:", e);
    return "";
  }
};

// 处理用药情况
const getMedicationText = () => {
  try {
    const medication = JSON.parse(ruzhuData.value.medicationInfo || '{"list": []}');
    const drugNames = medication.list?.map(item => item.drugName || "未知药物") || [];
    return drugNames.length > 0 ? drugNames.join("、") : "无";
  } catch (e) {
    console.error("用药情况解析失败:", e);
    return "无";
  }
};

// 计算总费用
const calculateTotalFee = () => {
  const {
    nursingFee = 0,
    bedFee = 0,
    otherFee = 0,
    medicalInsurancePayment = 0,
    governmentSubsidy = 0,
  } = ruzhuData.value;
  const total = nursingFee + bedFee + otherFee - medicalInsurancePayment - governmentSubsidy;
  return Math.max(total, 0).toFixed(2);
};

// 合同状态标签类型
const getContractTagType = () => {
  const status = ruzhuData.value.contractStatus;
  switch (status) {
    case "待生效": return "warning";
    case "已生效": return "success";
    case "已过期": return "info";
    case "已作废": return "danger";
    default: return "default";
  }
};

// 步骤条点击事件
const handleStepClick = (step) => {
  activeStep.value = step.index;
};
</script>

<style scoped>
/* 页面容器样式 */
.page-wrapper {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 卡片容器样式 */
.detail-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 1000px;
  margin: 20px auto;
}

/* 卡片通用样式 */
.detail-card {
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafbfc;
}

.card-icon {
  color: #409eff;
  margin-right: 8px;
  font-size: 18px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

/* 卡片内容样式 */
.card-content {
  padding: 24px;
}

/* 信息列表布局 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 信息项样式 */
.info-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 信息标签 */
.info-label {
  font-size: 13px;
  color: #666;
  width: 120px;
  text-align: right;
  flex-shrink: 0;
}

/* 信息值 */
.info-value {
  font-size: 14px;
  color: #333;
  flex-grow: 1;
  word-wrap: break-word;
}

/* 评估模块样式 */
.assessment-wrap {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.assessment-item {
  padding-bottom: 16px;
  border-bottom: 1px dashed #f0f0f0;
}

.assessment-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.assessment-title {
  font-size: 15px;
  font-weight: 500;
  color: #409eff;
  margin-bottom: 16px;
  padding-left: 4px;
  border-left: 3px solid #409eff;
}

/* 文本颜色样式 */
.text-primary { color: #409eff; }
.text-success { color: #67c23a; }
.text-danger { color: #f56c6c; }
.text-warning { color: #e6a23c; }
.font-bold { font-weight: 500; }

/* 响应式适配 */
@media (max-width: 768px) {
  .detail-container { max-width: 100%; }
  .card-content { padding: 16px; }
  .info-item { gap: 8px; }
  .info-label { width: 100px; text-align: left; }
  .page-wrapper { padding: 10px; }
}
</style>